package com.bs.service;

import com.bs.domain.AlertType;
import com.bs.domain.AlertUser;
import com.bs.repository.AlertTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by wujian
 * Date: 2017-12-08
 * Time: 15:11
 */
@Service
@Transactional
public class AlertTypeService {
    @Autowired
    private AlertTypeRepository alertTypeRepository;

    public List<AlertType> query(AlertType alertType){
        return alertTypeRepository.findAll(where(alertType));
    }

    public void save(AlertType alertType){
        alertTypeRepository.save(alertType);
    }

    public void delete(AlertType alertType){
        alertTypeRepository.delete(alertType);
    }

    /**
     * 条件查询时动态组装条件
     */
    private Specification<AlertType> where(AlertType alertType) {
        return new Specification<AlertType>() {
            @Override
            public Predicate toPredicate(Root<AlertType> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<Predicate>();

                if (alertType.getAlertName() != null && !alertType.getAlertName().equals("")) {
                    predicates.add(cb.like(root.<String>get("alertName"), "%" + alertType.getAlertName() + "%"));
                }
                return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };
    }
}
